<template>
  <div class="domain">
    <n-scrollbar style="max-height: calc(100% - 60px); padding-right: 10px;">
      <div v-show="store.navId == 1">
        <div class="search-box">
          <n-input v-model:value="searchQuery" placeholder="搜索聊天" clearable @input="filterSessions" />
        </div>
        <template v-if="filteredSessionList && filteredSessionList.length > 0">
          <div :class="['session-item', { 'session-active': item.FormId == store.sessionSelectId }]" v-for="item in filteredSessionList" :key="item.Id" @click="selectSession(item)">
            <div class="session-img">
              <n-badge :value="getUnReadCount(item.FormId)">
                <n-avatar size="medium" :src="item.Avatar"></n-avatar>
              </n-badge>
            </div>
            <div class="session-content">
              <div class="session-name text-ellipsis">{{ item.Name }}</div>
              <div class="session-desc text-ellipsis" v-html="getLastSession(item.FormId)"></div>
            </div>
          </div>
        </template>
        <div class="empty-session" v-else>
          <img class="empty-img" src="../assets/img/empty.png" alt="" />
          <div class="empty-text">暂无会话</div>
        </div>
      </div>
      <div v-show="store.navId == 2">
        <div class="search-box">
          <n-input v-model:value="searchQueryUser" placeholder="搜索用户" clearable @input="filterUsers" />
        </div>
        <template v-if="filteredGroupedSessionList && Object.keys(filteredGroupedSessionList).length > 0">
          <div v-for="(group, letter) in filteredGroupedSessionList" :key="letter">
            <div class="group-header"><span class="letter">{{ letter }}</span></div>
            <div :class="['session-item', { 'session-active': item.Id == store.allSessionSelectId }]" v-for="item in group" :key="item.FormId" @click="selectSession(item)">
              <div class="session-img">
                <n-avatar size="medium" :src="item.Avatar"></n-avatar>
              </div>
              <div class="session-content">
                <div class="session-name text-ellipsis">{{ item.Name }}</div>
              </div>
            </div>
            <div class="divider"></div>
          </div>
        </template>
        <div class="empty-session" v-else>
          <img class="empty-img" src="../assets/img/empty.png" alt="" />
          <div class="empty-text">暂无会话</div>
        </div>
      </div>
    </n-scrollbar>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch, onBeforeUnmount, onMounted } from "vue";
import Conversition from "../class/Conversition";
import { useMainStore } from "../store/index";
const store:any= useMainStore();
import User from "../class/User";
import { pinyin } from 'pinyin-pro'; // 需要安装 pinyin 库

// 搜索框输入值
const searchQuery = ref("");
const searchQueryUser = ref("");

// 过滤后的会话列表
let filteredSessionList = ref<User[]>([]);

// 分组后的会话列表
const groupedSessionList = computed(() => {
  const grouped: { [key: string]: User[] } = {};
  store.allSessionList.forEach((item: User) => {
    const firstLetter = pinyin(item.Name[0], { style: pinyin.STYLE_FIRST_LETTER })[0][0].toUpperCase();
    if (!grouped[firstLetter]) {
      grouped[firstLetter] = [];
    }
    grouped[firstLetter].push(item);
  });
  return grouped;
});

onMounted(() => {
  filteredSessionList.value = store.sessionList;
});

// 过滤后的分组会话列表
const filteredGroupedSessionList = computed(() => {
  if (!searchQueryUser.value) return groupedSessionList.value;
  const filtered: { [key: string]: User[] } = {};
  Object.keys(groupedSessionList.value).forEach(letter => {
    const group = groupedSessionList.value[letter].filter(item =>
      item.Name.toLowerCase().includes(searchQueryUser.value.toLowerCase())
    );
    if (group.length > 0) {
      filtered[letter] = group;
    }
  });
  return filtered;
});

// 获取未读消息数量
const getUnReadCount = computed(() => {
  return (id: Number) => {
    return getUnReadCountById(id);
  };
});

// 获取消息最后一条内容
const getLastSession = computed(() => {
  return (id: Number) => {
    let currentContent: Array<Conversition> = store.conversitionList.filter(
      (x: Conversition) =>
        (x.SendId == store.sender.Id && x.ReciverId == id) ||
        (x.SendId == id && x.ReciverId == store.sender.Id)
    );
    let result = "";
    if (currentContent.length > 0) {
      let len = currentContent.length - 1;
      switch (currentContent[len].Type) {
        case 0:
          result = currentContent[len].Content;
          break;
        case 1:
          result = "图片";
          break;
        case 2:
          result = "视频";
          break;
        case 3:
          result = "语音";
          break;
      }
    }
    return result;
  };
});

// 根据Id获取未读消息数量
function getUnReadCountById(id: Number) {
  let currentContent = store.conversitionList.filter(
    (x: Conversition) =>
      x.SendId == id && x.ReciverId == store.sender.Id && !x.ReadFlag
  );
  return currentContent.length > 999 ? "999+" : currentContent.length;
}

// 选择会话用户
function selectSession(item: any) {
  if (store.navId == 1) {
    store.sessionSelectId = item.FormId;
    store.reciver = item;
    store.reciver.Id = item.FormId;
    store.toTop();
    store.changeReaded(item.FormId);
    store.initEditor();
  } else if (store.navId == 2) {
    store.allSessionSelectId = item.FormId || item.Id;
    store.readyReciver = item;
  }
}

// 过滤和排序会话列表
function filterSessions() {
  if (searchQuery.value) {
    filteredSessionList.value = store.sessionList
      .filter((item: any) =>
        item.Name.toLowerCase().includes(searchQuery.value.toLowerCase())
      )
      .filter((item: { Id: any; }, index: any, self: any[]) => self.findIndex(t => t.Id === item.Id) === index) // 去重
      .sort((a: User, b: User) => a.Name.localeCompare(b.Name));
  } else {
    filteredSessionList.value = store.sessionList
      .filter((item: { Id: any; }, index: any, self: any[]) => self.findIndex((t: { Id: any; }) => t.Id === item.Id) === index) // 去重
      .sort((a: User, b: User) => a.Name.localeCompare(b.Name));
  }
}

// 过滤和排序用户列表
function filterUsers() {
  // 这里不需要对用户列表进行过滤，只需要对分组后的用户列表进行过滤
}

// 监听 store.sessionList 变化
watch(
  () => store.sessionList,
  () => {
    filterSessions();
  },
  { immediate: true }
);

// 监听 store.allSessionList 变化
watch(
  () => store.allSessionList,
  () => {
    filterUsers();
  },
  { immediate: true }
);

// 组件卸载时清空 filteredSessionList
onBeforeUnmount(() => {
  filteredSessionList.value = [];
});
</script>

<style scoped lang="less">
.domain {
  height: 100%;
  width: 20%;
  background: white;
  border-right: 1px solid #eaeaea;
  padding: 16px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;

  .search-box {
    height: 50px;
    margin-bottom: 16px;
    width: 100%;
  }

  .empty-session {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    color: #999;
    .empty-img {
      width: 100px;
      height: auto;
    }

    .empty-text {
      margin-top: 10px;
      font-size: 14px;
    }
  }

  .group-header {
    font-size: 10px;
    font-weight: bold;
    position: relative;
    color: gray;
    margin-top: 16px;
    margin-bottom: 8px;

    .letter {
      margin-right: 65%
    }
  }

  .session-item {
    height: 80px;
    width: 100%;
    display: flex;
    align-items: center;
    padding: 0 20px;
    cursor: pointer;
    border-radius: 8px;
    margin-bottom: 8px;
    transition: background-color 0.3s;

    &:hover {
      background-color: #f5f5f5;
    }

    .session-img {
      width: 30%;
      display: flex;
      justify-content: center;
    }

    .session-content {
      width: 60%;
      margin-left: 10%;
      text-align: left;
      overflow-y: auto; /* 确保内容可滚动 */

      .session-name {
        color: black;
        font-size: 16px;
      }

      .session-desc {
        font-size: 12px;
        margin-top: 6px;
        color: black;
        display: flex;
        height: 20px;

        /deep/ * {
          padding: 0;
          margin: 0;
        }

        /deep/ img {
          height: 20px !important;
          width: 20px !important;
        }
      }

      /* 自定义滚动条样式 */
      &::-webkit-scrollbar {
        width: 10px;
        position: absolute;
        right: 0;
      }

      &::-webkit-scrollbar-track {
        background: #f1f1f1;
      }

      &::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 5px;
      }

      &::-webkit-scrollbar-thumb:hover {
        background: #555;
      }
    }
  }

  .session-active {
    background-color: #e0f7fa;
    font-weight: bold;
  }

  .divider {
    height: 1px;
    background-color: #eaeaea;
    margin: 16px 0;
  }
}
</style>